const Service = require('egg').Service;

var uuid = require('uuid');

class DatabaseService extends Service {

	async databases () {

		const res = await this.app.mysql.get('sys').query(
			' show databases '
		);

		return res;
	}

	async tables (db) {
		const res = await this.app.mysql.get(db).query(
			' select table_name from information_schema.tables where table_schema=? and  table_type="base table" ', [db]
		);
		return res;
	}


	async cols (tablename, multiple, db) {

		if(multiple == undefined){
			const res = await this.app.mysql.get(db).query(
				' select column_name, column_comment from information_schema.columns where table_schema=? and table_name=? ', [db, tablename]
			);

			return res;
		}else{
			const arr = tablename.split(',');
			let obj = {};

			for(let i = 0; i < arr.length; i++){
				const tmp = arr[i];
				if(tmp == '') continue;

				const res = await this.app.mysql.get(db).query(
					' select column_name from information_schema.columns where table_schema=? and table_name=? ', [db, tmp]
				);
				obj[tmp] = res;
			}

			console.log('return');
			console.log(obj);
			return obj;
		}


		
	}


	async createApi (para) {

		const conn = this.app.mysql.get('sys');

		const { id, ...p } = para;

		console.log(id);

		console.log(p);

		let res = null;
		if(id != undefined){
			res = await conn.update('dlq_page', {
				...para,
				update_time : conn.literals.now,
			});
		}else{
			res = await conn.insert('dlq_page', {
				'id' : uuid.v1(),
				...p,
				create_time : conn.literals.now,
				update_time : conn.literals.now,
			});
		}

		return res;
	}

	async getApi (name) {
		const conn = this.app.mysql.get('sys');
		const res = await conn.get('dlq_page', {
			name,
		});

		console.log('res');
		console.log(res);
		console.log(name);

		await this.app.redis.get('system').hset('dlq_sql', name, res.json);

		return res.json;
	}
}

module.exports = DatabaseService;